#!/bin/bash

# execute dependency check (if file exists)
if [ -e check.part.bash ]; then
	echo "Checking dependencies .."
	if ! bash check.part.bash 1>&2; then
		echo "** Error: Dependency check failed" 1>&2
		exit 1
	fi
	echo "Dependency check succeeded"
fi

. config
DIR=$HOME/.deploy
mkdir -p $DIR

UNINSTALLED=0

# uninstall previous deployment
if [ -e $DIR/master.uninstall.bash ]; then
	echo "Uninstalling previous software bundle"
	UNINSTALLED=1
	( cd $DIR; bash master.uninstall.bash 1>&2 )
fi

# some files were left!
if [ ! -z "`ls -A $DIR`" ]; then
	echo "Previous bundle uninstallation was messy. Cleaning up"
	rm -rf $DIR/*
fi

echo "Copying new application files"
for fname in ${FILES[@]}; do
	mkdir -p `dirname $DIR/$fname`
	cp $fname $DIR/$fname
done

echo "Copying new platform files"
cp run.bash bundlepeer check.part.bash install.part.bash master.uninstall.bash uninstall.part.bash config $DIR/ 2>/dev/null
cp "$NAME-$VERSION.stuff" $DIR/


# execute install.part (if exists)
if [ -e $DIR/install.part.bash ]; then
	echo "Executing application install script"
	if ! ( cd $DIR && bash install.part.bash ); then
		echo "** Error in application install script" 1>&2
		echo "** Roll back.." 1>&2
		rm -rf $DIR
		
		if [ $UNINSTALLED -eq 1 ]; then
			echo "** Could not restore previous application. Rover is wiped!"
		fi
		
		exit 1
	fi
fi


echo "Setting autostart program to application"
max-autostart bash $DIR/run.bash "$DIR"

echo "Starting application as background process"
max-client -kad

echo "=== Successful install! ==="

